<template>
  <view class="baseForm">
    <!-- 搜索&扫码 -->
    <!-- <view class="upload-scan">
			<u-search
				v-model="searchText"
				shape="round"
				bgColor="#fff"
				:show-action="true"
				actionText="搜索"
				placeholder="请输入设备编号或名称"
				:animation="true"
				class="search"
				@search="searchList"
				@clear="searchList"
				@custom="searchList"></u-search>
			<u-icon
				name="scan"
				size="27px"
				:bold="false"
				@click="scanHandle"></u-icon>
		</view> -->
    <view
      class="flex justify-between"
      style="padding: 0 10px; margin-bottom: 1px; padding-top: 1px">
      <view @click="showPositionPicker" class="flex input-box-position">
        <u--input
          v-model="position"
          prefixIcon="search"
          border="none"
          placeholder="请选择位置"
          readonly
          class="input-self"></u--input>
        <image
          @click.stop="clearInfo()"
          v-show="position"
          src="@/static/image/delete.png" />
      </view>
    </view>
    <!-- 搜索&扫码 -->
    <view class="upload-scan-device" style="margin-top: 5px">
      <view class="flex select-device-form">
        <u-icon
          name="scan"
          size="24px"
          :bold="false"
          @click="scanHandle"></u-icon>
        <u-search
          v-model="searchText"
          shape="round"
          bgColor="#fff"
          :show-action="true"
          actionText="搜索"
          :animation="true"
          placeholder="请输入设备编号"
          class=""
          searchIcon=""
          @search="searchList"
          @clear="searchList"
          @custom="searchList"></u-search>
      </view>
      <u-button
        style="width: 50px; min-width: 50px; margin-right: 2px"
        size="small"
        type="primary"
        text="选择"
        @click="jump1('/eam/equ/selectDevice/index')"></u-button>
    </view>

    <!-- tab-bar切换 -->
    <view class="tab-bar">
      <u-tabs
        :current="activeTab"
        :list="tabList"
        :scrollable="false"
        :activeStyle="{
          color: '#007aff',
          fontWeight: 'bold',
        }"
        lineWidth="34px"
        lineHeight="2px"
        lineColor="#007aff"
        @change="changeTab"></u-tabs>
    </view>

    <!-- 当前作业 -->
    <view class="activeHeight">
      <!-- 列表 -->
      <u-list
        ref="tableScroll"
        @scrolltolower="scrolltolower"
        class="list"
        v-if="total"
        :height="listHeight"
        lowerThreshold="50px"
        :pagingEnabled="true">
        <u-list-item v-for="(item, index) in tableList" :key="item.id">
          <view class="card">
            <view class="flex record-title">
              <text class="line1">
                {{ item.orderNo }}
              </text>
              <text :class="'orange-color'">
                {{
                  useDictionaryStore().filterDictName(
                    "RepairOrderStatus",
                    item.orderStatus
                  )
                }}
              </text>
            </view>
            <view
              class="flex flex-col justify-between flex-1 h-full record-content-body">
              <view class="record-content" @click="jumpChange(item)">
				  <view class="record-item">
				    <text>计划名称</text>
				    <text>{{ item?.planName || "" }}</text>
				  </view>
                <view class="record-item">
                  <text>设备名称</text>
                  <text>{{ item?.assetName || "" }}</text>
                </view>
                <view class="record-item">
                  <text>设备编号</text>
                  <text>{{ item?.assetCode || "" }}</text>
                </view>
                <view class="record-item">
                  <text>维修内容</text>
                  <view
                    class="line1"
                    style="width: calc(750rpx - 30px - 140px); display: block">
                    {{ item?.repairContent || "" }}
                  </view>
                </view>

                <view class="record-item">
                  <text>计划维修日期</text>
                  <text>
                    {{ dayjs(item?.planStartTime).format("YYYY-MM-DD") }}
                  </text>
                </view>

                <view class="record-item">
                  <text>维修班组</text>
                  <text>{{ item?.executeTeamName }}</text>
                </view>
                <view class="record-item" v-if="item?.repairUserName">
                  <text>主修人</text>
                  <text>{{ item?.repairUserName }}</text>
                </view>
              </view>
            </view>
            <!-- <view v-show="item.repairStatus>2" class="mt-4"></view> -->
            <view v-show="item.orderStatus != '2'" class="record-footer">
              <button
                class="record-btn orange-btn"
                v-if="item.orderStatus == 0"
                @click="openPrompt(item, 1)">
                开始维修
              </button>
              <button
                v-if="item.orderStatus == 1"
                @click="
                  jumpEdit(
                    '/eam/equ/plannedMaintenance/planndeEdit',
                    item.id,
                    '0'
                  )
                "
                class="record-btn reach">
                维修
              </button>
            </view>
          </view>
        </u-list-item>
      </u-list>
      <view class="flex justify-center" v-show="tableLoading">
        <u-loading-icon color="#000a7b"></u-loading-icon>
      </view>
      <!-- 空数据 -->
      <view v-show="tableList.length === 0 && !tableLoading">
        <u-empty
          mode="list"
          icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
      </view>
    </view>

    <!-- <u-button text="立即报修" color="#0F40F5" class="first-btn" @click="jumpEdit('/eam/equ/repairOrderCreate/index')"></u-button> -->

    <u-modal
      :show="showImport"
      ref="uModal"
      :content="promptText"
      confirmText="确认"
      showCancelButton
      @cancel="cancelImport"
      @confirm="confirmImport">
      <view class="slot-content">
        <text v-show="promptStatus !== 6">{{ promptText }}</text>
      </view>
    </u-modal>
    <!-- 树形选择器 -->
    <ba-tree-picker
      ref="positionPicker"
      :multiple="false"
      @select-change="positionChange"
      title="位置"
      :selectedData="showPositionValue"
      :localdata="positionList"
      valueKey="id"
      textKey="locationName"
      childrenKey="nodes" />
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from "vue";
import {
  onShow,
  onPullDownRefresh,
  onLoad,
  onBackPress,
} from "@dcloudio/uni-app";
import { http } from "@/utils/http";
import { PageResult, TabInfo } from "@/types/type";
import { getSecondTime } from "@/utils/common";
import { useDictionaryStore } from "@/stores/useDictionaryStore";
import { toScanCode } from "@/components/hs-scancode/scan.js";
import { useEamStore } from "@/stores/useEamStore";

// import mumuGetQrcode from '@/uni_modules/mumu-getQrcode/components/mumu-getQrcode/mumu-getQrcode.vue';
const promptText = ref("");
import dayjs from "dayjs";
const promptStatus = ref(null);
const promptReason = ref("");
function getStatusText(item, status) {
  promptReason.value = "";
  if (status === 1) {
    promptText.value = `请确认，是否开始维修编号为${item.orderNo}的报修单?`;
  }
  // else if (status === 2) {
  // 	promptText.value = `请确认，编号为${item.repairCode}的报修单是否返修?`;
  // } else if (status === 6) {
  // 	promptText.value = `请填写故障关闭原因`;
  // }
}

function qrcodeSucess(data) {
  uni.showModal({
    title: "成功",
    content: data,
    success: () => {
      // uni.navigateBack({})
    },
  });
}
function qrcodeError(err) {
  console.log(err);
  uni.showModal({
    title: "摄像头授权失败",
    content: "摄像头授权失败，请检测当前浏览器是否有摄像头权限。",
    success: () => {
      // uni.navigateBack({})
    },
  });
}

const activeTab = ref(0);
const searchPars = ref(["0", "1"]);
// const tabList = [{ name: '待维修' }, { name: '已维修' }];
const tabList = computed(() => [
  { name: `待维修(${totalOne.value ?? 0})` },
  { name: `已维修(${totalTwo.value ?? 0})` },
]);
function changeTab(val: TabInfo) {
  searchPars.value = ["0", "1"];
  if (val.index == 0) {
    searchPars.value = ["0", "1"];
  } else if (val.index == 1) {
    searchPars.value = ["2", "3"];
  }
  activeTab.value = val.index;
  searchList();
}

// 待完成数据
const tableList = ref([]);
const tableLoading = ref(false);
const current = ref(0);
const totalPage = ref(0);
const total = ref(0);

//列表高度
const listHeight = ref("");

onLoad(() => {
  // #ifdef H5
  listHeight.value = "calc(100vh - 88px - 44px - 40px)";
  // #endif

  // #ifdef APP-PLUS
  listHeight.value = "calc(100vh - 48px - 44px - 40px)";
  // #endif
  // loadmore();
});

onShow(() => {
  searchList();
  getNumber();
});

onPullDownRefresh(() => {
  searchList();
});

// async function loadmore(type?: string) {
// 	try {
// 		current.value += 1;
// 		tableLoading.value = true;
// 		const result: PageResult<any> = await http({
// 			method: "POST",
// 			url: "eam/eamplanrepairorder/getListByLoginUser",
// 			data: {
// 				current: current.value,
// 				size: 20,
// 				data: {
// 					progressStatus: activeTab.value,
// 					assetInfo: searchText.value,
// 				},
// 			},
// 		}).finally(() => {
// 			tableLoading.value = false;
// 		});
// 		const list = result.data;
// 		for (let i = 0; i < list.length; i++) {
// 			tableList.value.push(list[i]);
// 		}
// 		totalPage.value = result.page;
// 		total.value = result.total;
// 		type === "refresh" && uni.stopPullDownRefresh();
// 	} catch (e) {
// 		console.log(e);
// 	}
// }
const searchContent = ref("");
async function loadmore(type?: string) {
  try {
    current.value += 1;
    tableLoading.value = true;
    const result: PageResult<any> = await http({
      method: "POST",
      url: "/eam/eamplanrepairorder/getListByLoginUser",
      data: {
        current: current.value,
        size: 20,
        data: {
          locationId: positionId.value,
          orderStatuses: searchPars.value,
          searchContent: searchText.value,
          // orderStatuses: ["2"],
        },
      },
    }).finally(() => {
      tableLoading.value = false;
    });
    const list = result.data;
    for (let i = 0; i < list.length; i++) {
      tableList.value.push(list[i]);
    }
    console.log(tableList.value);
    totalPage.value = result.page;
    total.value = result.total;
    if (searchPars.value.includes("0")) {
      totalOne.value = result.total;
    }
    if (searchPars.value.includes("2")) {
      totalTwo.value = result.total;
    }
    type === "refresh" && uni.stopPullDownRefresh();
  } catch (e) {
    console.log(e);
  }
}

const scrolltolower = () => {
  totalPage.value > current.value && loadmore();
};

// 选择作业
const selectInfo = ref({});
const showImport = ref(false);
function openPrompt(row, status) {
  promptStatus.value = status;
  getStatusText(row, status);
  showImport.value = true;
  selectInfo.value = row;
}

// 取消选择
function cancelImport() {
  showImport.value = false;
  selectInfo.value = {};
}

function changeStatus() {
  return new Promise(async (resolve, reject) => {
    const res = await http({
      method: "POST",
      url: "/eam/eamplanrepairorder/start",
      data: {
        id: selectInfo.value.id,
      },
    }).catch((e) => {
      // showImport.value = false;
    });
    resolve(res);
  });
}
// 追加加工单
async function confirmImport() {
  const { code } = await changeStatus();
  if (code === 200) {
    uni.showToast({
      title: "操作成功",
    });
    // if (promptStatus.value === 2) {
    // 	jumpEdit("/eam/equ/repairHandle/edit", selectInfo.value.id, "0");
    // } else {
    // 	searchList();
    // }
    searchList();
  } else {
    uni.showToast({
      title: "操作失败",
    });
  }
  showImport.value = false;
}

// H5端扫码调用
const showMumuQrcode = ref(false);

// 点击扫码
const searchText = ref("");
// function openScan() {
// 	/* #ifdef H5 */
// 	uni.showToast({
// 		icon: "none",
// 		title: "请到安卓设备进行扫码",
// 	});
// 	showMumuQrcode.value = true;
// 	/* #endif */
// 	// 只允许通过相机扫码
// 	uni.scanCode({
// 		scanType: ["barCode", "qrCode"],
// 		onlyFromCamera: true,
// 		success: function (res) {
// 			searchText.value = JSON.stringify(res.result);
// 			searchList();
// 			console.log("条码类型：" + res.scanType);
// 			console.log("条码内容：" + res.result);
// 		},
// 	});
// }

function scanHandle() {
  toScanCode({
    onlyFromCamera: true, // 只允许通过相机扫码
  })
    .then((res) => {
      uni.showToast({
        icon: "success",
        title: "扫码成功",
      });
      searchText.value = res;
      searchList();
    })
    .catch((e) => {
      uni.showToast({
        icon: "error",
        title: e,
      });
    });
}

// 列表搜索
function searchList() {
  current.value = 0;
  tableList.value = [];
  loadmore("refresh");
}

// 网页跳转
function jump(item, id = "") {
  uni.navigateTo({
    url: id ? `/pages${item}?id=${id}` : `/pages${item}`,
    fail: () => {
      uni.showToast({
        title: "敬请期待",
        icon: "error",
      });
    },
  });
}

function jumpEdit(item, id = "", read = "0", orderStatus = "") {
  uni.navigateTo({
    url: `/pages${item}?assetKind=3&id=${id}&isRead=${read}&orderStatus=${orderStatus}`,

    fail: () => {
      uni.showToast({
        title: "敬请期待",
        icon: "error",
      });
    },
  });
}

function jumpChange(item) {
  if (item.orderStatus == 1) {
    jumpEdit(
      "/eam/equ/plannedMaintenance/planndeEdit",
      item.id,
      "0",
      item.orderStatus
    );
  } else if (item.orderStatus == 2) {
    jumpEdit(
      "/eam/equ/plannedMaintenance/planndeEdit",
      item.id,
      "1",
      item.orderStatus
    );
  } else if (item.orderStatus == 3) {
    jumpEdit(
      "/eam/equ/plannedMaintenance/planndeEdit",
      item.id,
      "0",
      item.orderStatus
    );
  }

  // activeTab == "0" && item.orderStatus == 1
  // 	? jumpEdit("/eam/equ/plannedMaintenance/planndeEdit", item.id, "0")
  // 	: activeTab == "1" && item.orderStatus == 2
  // 	? jumpEdit("/eam/equ/plannedMaintenance/planndeEdit", item.id, "1")
  // 	: "";
}
function jump1(item) {
  uni.navigateTo({
    url: `/pages${item}?isReturn=1`,
    fail: () => {
      uni.showToast({
        title: "敬请期待",
        icon: "error",
      });
    },
  });
}

// 新加的位置与设备选择功能如下

// 选择位置信息
const selectedPosition = computed(() =>
  JSON.parse(useEamStore().selectedPosition)
);

// 显示选择器
const positionId = ref("");
const position = ref("");
const positionPicker = ref();
function showPositionPicker() {
  positionPicker.value._reTreeList();
  positionPicker.value._show();
}
//监听选择（ids为数组）
const showPositionValue = ref([]);
function positionChange(ids, names) {
  console.log("ids", ids, names);
  positionId.value = ids[0] ?? "";
  position.value = names ?? "";
  showPositionValue.value = ids[0] ? [ids[0]] : [];
  useEamStore().setSelectedPosition({
    positionId: ids[0] ?? "",
    positionName: names ?? "",
  });
  if (ids.length) {
    searchList();
  }
}

// 清空数据
function clearInfo() {
  positionId.value = "";
  position.value = "";
  useEamStore().setSelectedPosition({});
  showPositionValue.value = [];
  if (positionPicker.value?._reTreeList) {
    positionPicker.value._reTreeList();
  }
  searchList();
}
// 获取位置列表
const positionList = ref();
async function getPositionList() {
  const { data } = await http({
    method: "POST",
    url: `/eam/locationInfo/getTree`,
    data: {},
  });
  positionList.value = data;
}
onLoad(() => {
  useEamStore().setDeviceList();
  useEamStore().setSelectedPosition({});
  getPositionList();
});
// 选择设备信息
const deviceList = computed(() => JSON.parse(useEamStore().deviceList));
// 监控设备选择id
watch(
  () => deviceList,
  async (newVal) => {
    if (newVal.value[0]?.id) {
      searchText.value = newVal.value[0]?.assetCode;
      searchList();
    }
    setTimeout(() => {
      useEamStore().setDeviceList();
    }, 1000);
  },
  {
    deep: true,
    immediate: true,
  }
);
onBackPress(() => {
  back1();
  return true;
});
const back1 = () => {
  uni.switchTab({
    url: "/pages/index/index",
  });
};

const totalOne = ref(null);
const totalTwo = ref(null);
const totalThree = ref(null);
const _m = [
  ["0", "1"],
  ["2", "3"],
];
const getNumber = async () => {
  _m.forEach(async (item) => {
    const result: PageResult<any> = await http({
      method: "POST",
      url: "/eam/eamplanrepairorder/getListByLoginUser",
      data: {
        current: current.value,
        size: 20,
        data: {
          locationId: positionId.value,
          orderStatuses: item,
          searchContent: searchText.value,
          // orderStatuses: ["2"],
        },
      },
    });
    if (item.includes("0")) {
      totalOne.value = result.total;
    }
    if (item.includes("2")) {
      totalTwo.value = result.total;
    }
  });
};
</script>

<style lang="scss" scoped>
uni-page-body {
  height: 100%;
  background-color: #fbfbff;
}

.search {
  :deep(.u-search__content) {
    box-shadow: 0 1px 8px 0px rgb(19 10 236 / 8%);
  }
}

.baseForm {
  background-color: #fbfbff;

  .tab-bar {
    padding: 0 20px;
  }

  .upload-scan {
    padding: $uni-page-padding;
    padding-top: 5px;
    padding-bottom: 5px;
    display: flex;
    align-items: center;

    // box-shadow: 0 1px 10px 0px rgb(19 10 236 / 10%);
    .u-icon {
      margin-left: 8px;
    }
  }

  .u-line {
    padding: 10px 0;
  }
}

.list {
  .card {
    margin: $uni-page-padding;
    margin-top: 5px;
    margin-bottom: 7px;
    border-radius: 7px;
    padding: 10px 12px 0px 12px;
    transition: all 300ms ease;
    box-shadow: 0 2px 6px rgba(3, 121, 255, 0.1);
    background-color: #fff;

    .card-flex {
      display: flex;
      align-items: flex-start;
    }

    .right {
      flex: 1;
    }

    .title {
      font-size: 14px;
      line-height: 40px;
      height: 40px;
      margin-top: 8px;
      font-weight: bold;
      color: #101010;
      border-top: 1px solid #e5ebff;
    }

    .uni-btn {
      float: right;
      font-size: 12px;
      height: 24px;
      line-height: 24px;
      padding: 0 15px;
      margin-top: 7px;
      font-weight: 400;
    }

    .des {
      font-size: 12px;
      line-height: 20px;
      margin-bottom: 3px;
    }

    .left {
      flex-basis: calc(50% + 10px);
    }
  }

  :deep(.u-list-item:nth-last-child(1)) {
    margin-bottom: 60px;
  }
}

.record-title {
  display: flex;
  justify-content: space-between;
  margin: 5px 0 3px 0;
  color: $primary-color;

  uni-text:nth-child(1) {
    font-weight: bold;
    font-size: 17px;
  }

  uni-text:nth-child(2) {
    font-size: 14px;
    min-width: 60px;
    text-align: right;
  }
}

.record-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 12px 0;
  border-top: 1px solid #f5f5f5;

  .record-btn {
    height: 30px;
    outline: none;
    border: none;
    line-height: 30px;
    border-radius: 30px;
    font-size: 14px;
    margin: 0px;
    margin-left: 10px;
    width: 100px;
  }
}

.u-loading-icon {
  margin: 8px 0;
}

.first-btn {
  position: fixed;
  bottom: 0;
  height: 42px;
  border-radius: 30px;
  margin: 10px 20px;
  width: calc(100% - 40px);
  font-size: 18px;

  :deep(.u-button__text) {
    font-size: 16px !important;
    font-weight: bold;
  }
}
</style>
